﻿using AutoMapper;
using MediatR;
using Traceability.Commont.DomainEvens;
using Traceability.Commont.Domains;
using Traceability.Commont.DTOs.CommontFiles;
using Traceability.Commont.Infrastructures.Interfaces;

namespace Traceability.Api.Applications.Userss
{
    public class UserCreateHander : IRequestHandler<UserCreateCommand, Resqults>
    {
        private readonly IBateRepository<Users> user;
        private readonly IBateRepository<UserRoles> userRoles;
        private readonly IMapper mapper;
        private readonly IMediator mediator;

        public UserCreateHander(IBateRepository<Users> user, IBateRepository<UserRoles> userRoles, IMapper mapper, IMediator mediator)
        {
            this.user = user;
            this.userRoles = userRoles;
            this.mapper = mapper;
            this.mediator = mediator;
        }

        public async Task<Resqults> Handle(UserCreateCommand request, CancellationToken cancellationToken)
        {
            Resqults res = new Resqults();
            var userInfo = mapper.Map<Users>(request);
            res.Code +=await user.Add(userInfo);

            foreach (var item in request.Ids)
            {
                var userRolInfo = new UserRoles()
                {
                    UserId = userInfo.UserId,
                    RolesId = item
                };
                res.Code +=await userRoles.Add(userRolInfo);
                //var userRoleCreateEven = new UserRolesCreateEven(userInfo.UserId, item);
                //await mediator.Publish(userRoleCreateEven);
            }
            return res;
        }
    }
}
